package com.onlyphoto.onlymall.mvp.view.fragment

import android.annotation.SuppressLint
import android.content.Context
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseFragment
import com.onlyphoto.onlymall.mvp.contract.CLoginBySms
import com.onlyphoto.onlymall.mvp.presenter.PLoginBySmsImpl

import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import cn.jpush.android.api.JPushInterface
import com.onlyphoto.onlymall.bean.request.SmsBean
import com.onlyphoto.onlymall.bean.response.UserInfoBean
import com.onlyphoto.onlymall.interfaces.PhoneCallback
import com.onlyphoto.onlymall.jpush.Util
import com.onlyphoto.onlymall.listeners.NoDoubleClickListener
import com.onlyphoto.onlymall.mvp.view.activity.LoginActivity
import com.onlyphoto.onlymall.utils.*
import kotlinx.android.synthetic.main.fragment_loginbysms.*
import kotlinx.android.synthetic.main.fragment_loginbysms.et_phone_number
import kotlinx.android.synthetic.main.fragment_loginbysms.login


class LoginBySmsFragment : BaseFragment<PLoginBySmsImpl>(), CLoginBySms.IVLoginBySms {

    private var callback: PhoneCallback? = null
    private var phone: String = ""

    override fun retry() {}

    override fun init() {
        phone = arguments!!.getString("phone", "")
        tv_verification.isEnabled = phone != ""
        et_phone_number.setText(phone)
        et_phone_number.setSelection(phone.length)

        //判断验证码是否需要继续计时
        val overTime = SharePreferenceUtil.getInstance(context).getLong(Constants.LOGIN_CODE_FINISH_TIME, 0)
        if (System.currentTimeMillis() < overTime) {
            //需要继续计时
            val remainderTime: Long = overTime - System.currentTimeMillis()
            tv_verification.startCountDownTime(remainderTime)
        }

        initListener()
    }

    fun initListener(){
        AndroidUtils.isButtonEnable(intArrayOf(11, 4), login, et_phone_number, et_sms_code)

        et_phone_number.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable) {
                tv_verification.isEnabled = s.length == 11
                phone = s.toString().trim()
            }
        })

        val listener = object: NoDoubleClickListener(){
            override fun onNoDoubleClick(view: View?) {
                when (view?.id) {
                    R.id.login -> {
                        mPresenter!!.loginBySms()
                    }
                    R.id.tv_verification -> {
                        tv_verification.setText("正在发送",false)
                        mPresenter!!.getVerify(2, phone)
                        //持久化验证码倒计时
                        SharePreferenceUtil.getInstance(context).setLong(Constants.LOGIN_CODE_FINISH_TIME, System.currentTimeMillis() + Constants.CODE_OVER_TIME * 1000)
                        //保存号码
                        SharePreferenceUtil.getInstance(context).setData(Constants.SHARE_TAG_LOGIN_PHONE, phone)
                    }
                }
            }
        }

        tv_verification.setOnClickListener(listener)
        login.setOnClickListener(listener)

    }

    override fun getLayoutRes(): Int {
        return R.layout.fragment_loginbysms
    }

    override fun createPresenter() {
        mPresenter = PLoginBySmsImpl(mContext, this)
    }

    override fun getVerifySuccess() {
        //获取验证码成功
        tv_verification.startCountDownTime()
        ToastUtil.showToast("验证码已发送")
    }

    override fun getVerifyFail() {
        tv_verification.reset()
        ToastUtil.showToast("验证码发送失败")
    }

    override fun showMsg(msg: String) {
        ToastUtil.showToast(msg)
    }

    override fun getLoginEntity(): SmsBean {
        val bean = SmsBean()
        bean.phone = et_phone_number.text.toString()
        bean.msg_code = et_sms_code.text.toString()
        return bean
    }

    override fun loginSuccess(bean: UserInfoBean) {
        UserUtil.saveUserInfo(activity, bean)
        SharePreferenceUtil.getInstance(activity).setBoolData(Constants.IS_PHONE_LOGIN, true)
        JPushInterface.setAlias(activity, 1, bean.user_alias)
        activity?.finish()
    }

    override fun showLoading() {
        defaultPostLoadingDialog?.isCancelable = false
        showDefaultDialog()
    }

    override fun hideLoading() {
        hideDefaultDialog()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            et_phone_number?.setText(LoginActivity.phoneNum)
            et_phone_number?.setSelection(LoginActivity.phoneNum!!.length)
        } else {
            val phone = et_phone_number?.text.toString().trim()
            callback?.phoneCange(phone)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        callback = context as PhoneCallback

    }

    companion object {

        fun newInstance(): LoginBySmsFragment {
            val fragment = LoginBySmsFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }
}
